package net.qiqbframework.common.sorting;

import net.qiqbframework.common.utils.AnnotationUtil;

import java.lang.reflect.AnnotatedElement;
import java.util.Comparator;

/**
 * 标注 {@link Priority} 的对象比较器
 *
 * @param <T>
 */
public class AnnotatedPriorityComparator<T> implements Comparator<T> {

    private static final AnnotatedPriorityComparator INSTANCE = new AnnotatedPriorityComparator();

    /**
     * 返回注解的优先级比较器的实例
     *
     * @param <T> 比较类型
     * @return 返回注解的优先级比较器的实例
     */
    @SuppressWarnings("unchecked")
    public static <T> AnnotatedPriorityComparator<T> getInstance() {
        return INSTANCE;
    }

    private AnnotatedPriorityComparator() {
    }

    @Override
    public int compare(T o1, T o2) {
        return Integer.compare(getPriority(o1.getClass()), getPriority(o2.getClass()));
    }

    private int getPriority(AnnotatedElement annotatedElement) {
        return AnnotationUtil.findAnnotationAttributes(annotatedElement, Priority.class).map(m -> (int) m.get("value")).orElse(Priority.NEUTRAL);
    }
}
